package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/gocarina/gocsv"
	"go.uber.org/atomic"
	"golang.org/x/sync/errgroup"
)

var (
	addr     *string
	interval *int

	restyCli *resty.Client
	visit    atomic.Int32
)

func init() {
	addr = flag.String("addr", "localhost", "server address")
	interval = flag.Int("i", 1, "request interval (second)")
	flag.Parse()

	log.SetFlags(log.LstdFlags | log.Lshortfile)
}

func main() {
	restyCli = resty.New().SetHostURL(fmt.Sprintf("http://%v:8080", *addr))
	file, err := os.OpenFile("robots.csv", os.O_RDONLY, os.ModePerm)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer file.Close()

	robots := make([]*robot, 0, 1000)
	if err := gocsv.UnmarshalFile(file, &robots); err != nil {
		log.Fatal(err.Error())
	}

	g := errgroup.Group{}
	for idx, r := range robots {
		func(r *robot) {
			g.Go(func() error {
				return r.Run()
			})
		}(r)

		if idx > 0 && idx%100 == 0 {
			time.Sleep(time.Second)
		}
	}

	g.Go(func() error {
		for range time.Tick(time.Second) {
			visit.Store(0)
		}
		return nil
	})

	_ = g.Wait()
}
